import { createRouter, createWebHashHistory } from 'vue-router'
import index from "@/components/index.vue";
import Login from "@/components/login.vue";
import Register from "@/components/register.vue";
import Personal from "@/components/personal.vue";
import Upload from "@/components/upload.vue";
import Apply_admin from "@/components/apply_admin.vue";
import Apply_admin_2 from "@/components/apply_admin_2.vue";
import Technology from "@/components/technology.vue";
import News from "@/components/news.vue";
import Article from "@/components/article.vue";
import Article2 from "@/components/article2.vue";
import Article3 from "@/components/article3.vue";
import Category from "@/components/category.vue";
import RequireLogin from "@/components/require-login.vue";

const isAuthenticated = () => {
  return localStorage.getItem('token');  // 假设 token 存储在 localStorage
};

const routes = [
  { path: '/', redirect: '/index' },
  {
    path: '/index',
    component: index
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: Register,
  },
  {
    path: '/personal',
    component: Personal,
    // meta: { requiresAuth: true }
  },
  {
    path: '/upload',
    component: Upload
  },
  {
    path: '/apply',
    component: Apply_admin
  },
  {
    path: '/apply2',
    component: Apply_admin_2
  },
  {
    path: '/technology',
    component: Technology
  },
  {
    path: '/news',
    component: News
  },
  {
    path: '/article',
    component: Article,
  },
  {
    path: '/article2',
    component: Article2,
  },
  {
    path: '/article3',
    component: Article3,
  },
  {
    path: '/category',
    component: Category,
  },
  {
    path: '/require-login',
    component: RequireLogin,
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});


router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated()) {
      // 如果未登录，重定向
      next({ path: '/login' });
    } else {
      next();
    }
  } else {
    // 如果路由不需要登录
    next();
  }
});

export default router;